package com.black.pay.handler;

import com.black.pay.cache.SessionCache;
import com.black.pay.cache.UserTokenCache;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

public class MyHandler extends TextWebSocketHandler {
    private SessionCache sessionCache;
    private UserTokenCache userTokenCache;
    @Override
    public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        String sessionId = session.getId();
        String reomteAddr = session.getRemoteAddress().getAddress().toString();
        System.out.println(session.getHandshakeHeaders().get("Cookie"));
        List<String> cookie =session.getHandshakeHeaders().get("Cookie");
        String key = null;
        for (String ck : cookie) {
            String[] cks=ck.split(";");
            for (String cok : cks) {
                String[] keyAndValue = cok.split("=");
                if ("token".equals(keyAndValue[0].trim())) {
                    key = keyAndValue[1].trim();
                    break;
                }
            }
        }
        sessionCache.save(key,session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        super.handleMessage(session, message);
        System.out.println("msg : "+message.toString());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        System.out.println("text : "+ message.getPayload());
    }

    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        super.handlePongMessage(session, message);
        System.out.println("pong");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        sessionCache.remove(session.getId());
    }

    @Override
    public boolean supportsPartialMessages() {
        return super.supportsPartialMessages();
    }

    public SessionCache getSessionCache() {
        return sessionCache;
    }

    public void setSessionCache(SessionCache sessionCache) {
        this.sessionCache = sessionCache;
    }

    public UserTokenCache getUserTokenCache() {
        return userTokenCache;
    }

    public void setUserTokenCache(UserTokenCache userTokenCache) {
        this.userTokenCache = userTokenCache;
    }
}
